var app = getApp();
var base64 = require('../../we7/resource/js/base64.js');
import GoEasy from './goeasy/goeasy-1.0.6';

Page({
    data:{
        siteroot : app.siteInfo.siteroot.replace('app/index.php', ''),uniacid: app.siteInfo.uniacid,
        showall : false,
        params : {},
        sharedata : {},
        beauty : 6.3,
        isSD : false,
        isFront : false,
        
        isShowAnimation : false,
        isNetBroken : false,
        cameraContext : '',
        animTimout : '',
        iswaiting : false,
        isHideGoods : false,
        isshowbag : true,
        isshowbot : true,
        istop : true,
        goods : [],
        info : {},
        timer : null,
        isplay : true,
        issxt : false,
        isstart : false,
        isjx : false,
        chouinfo : {},
        actgoods : {},
        isshowGoods : true,
        whiteness : 3,
        numtimer : null,
    },
    onShow(){
        var self = this;
        if( self.data.inited && self.data.isstart ){
            wx.setKeepScreenOn({
                keepScreenOn: true
            })
            self.createContext();
            self.resetAnimation();
            self.startAnimation();
        }
    },
    onUnload(){
        this.changelivestatus('stop');
        if(app.globalData.goEasy){
            app.globalData.goEasy.disconnect();
        }
    },
    onHide(){
        this.changelivestatus('stop');
    },
    onLoad:function(options){
        var self = this;
        var id = options.id ? options.id : '';
        id = options.scene ? options.scene : id;

        app.com.auth(function(user){
            app.com.http('live','POST',{op:'pusher',id:id},0,false,'','',function(res){
                if (!res.data.errno && res.data) {

                    self.setData({
                        info : res.data.data.info,
                        isBeauty : res.data.data.info.beauty*1 == 0 ? true : false,
                        isSD : res.data.data.info.hd*1 == 1 ? true : false,
                        isFront : res.data.data.info.front*1 == 1 ? true : false,

                        params : res.data.data.params,
                        sharedata : res.data.data.sharedata,
                        goods : res.data.data.goods ? res.data.data.goods : [],
                        chouinfo : res.data.data.chouinfo ? res.data.data.chouinfo : {},
                        actgoods : res.data.data.actgoods ? res.data.data.actgoods : {},
                        inited : true,
                    },function(){
                        self.initGo();
                        self.getNumber();
                    });
                    
                    wx.setKeepScreenOn({
                        keepScreenOn: true
                    })
                    self.createContext(true);
                    self.resetAnimation();
                    self.setData({
                        iswaiting : false,
                        isshowbag : true,
                        isplay : true,
                        isshowbot : true,
                        istop : true,
                    })
                    //self.startAnimation();
                    
                    wx.setNavigationBarTitle({
                        title: res.data.data.info.title
                    });
                }else{
                    app.com.alert(res.data.message,function(){
                        app.com.backPage(0);
                    });
                }
            });
        })
    },
    onShareAppMessage : function(){
        var self = this;
        return {
            title: self.data.sharedata.title,
            path: self.data.sharedata.path,
            imageUrl : self.data.sharedata.img,
        }
    },
    resetAnimation(){
        this.setData({
            isShowAnimation : false,
            iswaiting : true,
        })
    },
    getNumber(){
        var self = this;
        clearInterval(self.data.numtimer);
        self.data.numtimer = setInterval(function(){
            self.getNumberfn();
        },20000)
    },
    getNumberfn(){
        var self = this;
        var postdata = {
            op:'getnumber',
            id:self.data.info.id
        }
        app.com.http('live','POST',postdata,0,false,'','',function(res){
            if (!res.data.errno && res.data) {
                self.setData({
                    'info.scan' : res.data.data.scan,
                    'info.member' : res.data.data.member,
                    'info.zan' : res.data.data.zan,
                    'info.renqi' : res.data.data.renqi,
                    'info.totalrq' : res.data.data.totalrq,
                })
            }
        })
    },
    finished(){
        this.setData({
            'info.playstatus' : 10,
        })
        wx.setKeepScreenOn({
            keepScreenOn: true
        })
        this.createContext();
        this.resetAnimation();
        this.startAnimation();
    },
    startplay(){
        var self = this;
        this.setData({
            iswaiting : true,
            isshowbag : false,
            isplay : false,
            isshowbot : false,
            istop : false,
            isstart : true,
        },function(){
            self.startAnimation();
            setTimeout(function(){
                app.com.sendGo('{"type":"open","mtype":"open"}',self.data.info.code);
            },4000)
            
        })
    },
    setbeauty(e){
        this.setData({
            beauty : e.detail.beauty/10,
            whiteness : e.detail.whiteness/10,
        })
    },
    startAnimation(){
        var self = this;
        if(self.data.info.playstatus == 8 || self.data.info.playstatus == 9 || self.data.starting == 1) return false;
        this.data.starting = 1;
        this.setData({
            isShowAnimation : true,
        })
        this.data.animTimout && clearTimeout(this.data.animTimeout);

        this.data.animTimout = setTimeout(function() {

            self.data.cameraContext.stopPreview();
            self.data.cameraContext.start();
            
            self.data.starting = 0;
            self.setData({
                iswaiting : false,
                isshowbag : true,
                isplay : true,
                isshowbot : true,
                istop : true,
                isShowAnimation : false,
            })
            wx.showToast({
                icon: "none",
                title: "直播已开始，请保持微笑",
                success: function() {}
            })
            self.data.animTimout = null;
        },4000);
    },
    bindstatechange(e){
        var self = this;
        if(!this.data.isplay) return false;

        console.log("onPushEvent===========>", e);
        var code = e.detail.code;
        switch (code) {
            case 1002:
                console.log("1002 已经与服务器握手完毕,开始推流");
                break;
            case 1101:
                wx.showToast({
                    title: "当前网络环境较差，可切换网络后重新开播",
                    icon: "none"
                });
                break;
            case 1005:
                this.changelivestatus('play');
                break;   
            case 1006:
                this.changelivestatus('play');
                break;
            case 1007:
                this.changelivestatus('play');
                break;
            case 3005:
                wx.showToast({
                    title: "RTMP 读/写失败，发起直播失败，可能直播已结束了",
                    icon: "none"
                });
                this.changelivestatus('stop');
                break;
            case -1307:
                this.setData({
                    isNetBroken : true,
                })
                this.changelivestatus('stop');
                break;
            case 5e3:
                console.log("流被挂起");
                this.setData({
                    isPause : 1,
                })
                this.createContext();
                break;
            default:
                console.log(code, "code");
        }
        if(self.data.isPause){
            self.data.cameraContext.start({
                success: function(t) {
                    console.log("进入这里,success", t);
                    self.playing = !0, self.isPause = !1;
                    this.setData({
                        isPause : 0,
                        playing : 1,
                    })
                },
                fail: function(t) {
                    console.log("进入这里,fail", t);
                    this.setData({
                        isPause : 0,
                        playing : 0,
                    })
                }
            });
        }
    },
    netstatus(e){
        console.log(e)
    },
    showbag(e){
        this.setData({
            isshowGoods : e.detail == 1 ? false : true,
        })
    },
    showbotbar(e){
        this.setData({
            isshowbot :  e.detail == 1 ? false : true,
        })
    },
    showbagfn(){
        this.selectComponent('#goodsmask').onClose();
    },
    switch(e){
        this.setData({
            [e.detail.type] : e.detail.value
        })
        if(e.detail.type == 'issxt'){
            this.data.cameraContext.switchCamera();
        }
    },
    shareit(){
        this.selectComponent('#poster').onClose();
    },
    start: function() {
        var self = this;
        self.cameraContext.start({
            success: function(e) {
                t.playing = !0;
            },
            fail: function() {
                t.playing = !1;
            }
        });
    },
    closelive(){
        this.getNumberfn();
        this.setData({
            'info.playstatus' : 8,
        })
    },
    stop: function() {
        self.showAnimation = !1, this.isStop = !0;
    },
    pause: function() {
        self.data.cameraContext.pause();
    },
    resume: function() {
        self.data.cameraContext.resume();
    },
    hideGoods: function(e) {
        this.isHideGoods = !e.isHideGoods;
    },
    showGoods: function() {
        this.$refs.goodsMask.isShowGoods = !0;
    },
    createContext: function(ispre) {
        var self = this;
        if( self.data.cameraContext ){
            this.data.cameraContext = null;
            this.data.cameraContext = wx.createLivePusherContext("camera-push", this);
        }else{
            this.data.cameraContext = wx.createLivePusherContext("camera-push", this);
        }
        if(ispre){
            self.data.cameraContext.startPreview();
        }else{
            self.data.cameraContext.stopPreview();
            self.data.cameraContext.start();
        } 
    },
    addnewchou(e){
        this.setData({
            chouinfo : e.detail,
        })
        if(e.detail.isstart*1 == 1){
            this.selectComponent('#chou').startchou();
        }else{
            this.selectComponent('#chou').showp();
        }
    },
    initGo(){
        var self = this;
        app.globalData.goEasy = new GoEasy({
            host: self.data.params ? self.data.params.gosite : '', 
            appkey: self.data.params ? base64.base64_decode(self.data.params.gokey) : '',
            userId : self.data.params.uid,
            onConnected: function() {
                console.log('go连接成功！')
            },
            onDisconnected: function() {
                console.log('go连接断开！')
            },
            onConnectFailed: function(error) {
                console.log('go连接失败或错误！')
            }
        });

        app.globalData.goEasy.subscribe({
            channel: 'live'+self.data.info.code,
            onMessage: function (message) {
                self.setMessage(message.content);
            }
        });

        app.globalData.goEasy.subscribe({
            channel: 'pusher'+self.data.info.code,
            onMessage: function (message) {
                self.setMessage(message.content);
            }
        });

        self.getNoWnumer();
        clearInterval(self.data.timer);
        self.data.timer = setInterval(function(){
            self.getNoWnumer();
        },10000)

    },
    getNoWnumer(){
        var self = this;
        app.globalData.goEasy.hereNow({
            channels: ['live'+self.data.info.code],
            includeUsers: false,
            distinct: false
        },function(response) {
            //console.log(response)
            if(response.code == 200){
                let num = response.content.channels['live'+self.data.info.code].clientAmount;        
                self.selectComponent('#owner').changeNum({num:num});
            }
        })
    },
    setMessage(mess){
        var self = this;
        var content = JSON.parse(mess);  
        // 消息
        if(content.mtype == 'mess'){
            self.selectComponent('#chatbar').addMessage(content);
        }

        if(content.type == 'zan'){
            self.selectComponent('#bottombar').addzan();

        }else if(content.type == 'downgoods'){  
            self.setData({
                actgoods : false,
            })

        }else if(content.type == 'pushgoods'){          
            for (var i = 0; i < self.data.goods.length; i++) {
                if(self.data.goods[i].id*1 == content.gid*1){
                    self.setData({
                        actgoods : self.data.goods[i]
                    })
                }
            }
        }

        if(content.type == 'openchou'){
            self.selectComponent('#chou').upprize();
        }
        if(content.type == 'downlive'){
            this.setData({
                'info.playstatus' : 8,
            })
        }
    },
    changelivestatus(type){
        var postdata = {
            op : 'changelivestatus',
            status : type,
            liveid :  this.data.info.id,
        };
        app.com.http('live','POST',postdata,0,false,'','',function(res){});
    },
    showBubble(){
        this.selectComponent("#bubble").showBubble();
    },
    location : function( e ){
        app.com.location( e );
    },
    otherapp : function( e ){
        app.com.otherapp( e );
    },
    navigateto : function( e ){
        app.com.navigateto( e);
    },
    redirectto : function( e ){
        app.com.redirectto( e );
    },    
    callphone : function(e){
        app.com.callphone( e );
    },
    showimages : function( e ){
        app.com.showimages( e );
    },
    footNavigate(e){
        var url = e.currentTarget.dataset.url;
        wx.switchTab({
          url: url
        })
    },
    
})